package com.efounder.chat.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AlertDialog;
import android.text.Spannable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.fragment.ChatSenderFragment;
import com.efounder.chat.http.OKHttpUtils;
import com.efounder.chat.http.download.DownloadManager;
import com.efounder.chat.interf.DismissCallbacks;
import com.efounder.chat.item.FileMessageItem;
import com.efounder.chat.item.ImageMessageItem;
import com.efounder.chat.item.TextMessageItemForDes;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.item.manager.JFMessageItemManager;
import com.efounder.chat.manager.ChatMessageViewTypeDelegate;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.ChatDateUtils;
import com.efounder.chat.utils.ChatMessageMenuDialogUtil;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.IMStruct002Util;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.MessagePanSoftUtils;
import com.efounder.chat.utils.SmileUtils;
import com.efounder.chat.view.MessageBaseView;
import com.efounder.chat.view.MessageHideView;
import com.efounder.chat.view.MessageIncomingView;
import com.efounder.chat.view.MessageOutgoingView;
import com.efounder.chat.view.MessagePublicNumberView;
import com.efounder.chat.view.MessageRecallView;
import com.efounder.chat.widget.ChatListView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.JSONUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.efounder.chat.manager.ChatMessageViewTypeDelegate.VIEW_TYPE_INCOMMING;
import static com.efounder.chat.manager.ChatMessageViewTypeDelegate.VIEW_TYPE_OFFICIAL_ACCTOUNT;
import static com.efounder.chat.manager.ChatMessageViewTypeDelegate.VIEW_TYPE_OUTGOING;
import static com.efounder.chat.manager.ChatMessageViewTypeDelegate.VIEW_TYPE_SYSTEM;
import static com.efounder.chat.manager.ChatMessageViewTypeDelegate.VIEW_TYPE_TIPS;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.message.struct.IMStruct002.MESSAGE_STATE_DELIVER;


//import com.efounder.chat.item.LocationMapItem;

/**
 * 会话adapter
 */
public class ChatAdapter extends BaseAdapter implements OKHttpUtils.DownLoadCallBack {


    private final Context mContext;
    private List<IMStruct002> datas = null;
    private LXGlideImageLoader lxGlideImageLoader;
    private int myUserId;
    private ChatMessageViewTypeDelegate viewTypeDelegate;
    private Myhandler myhandler;
    private Boolean isHave = false;
    private JFMessageManager messageManager;
    private ChatSenderFragment.PreSendMessageCallback preSendMessageCallback = new ChatSenderFragment.PreSendMessageCallback() {
        @Override
        public void preSendMessage(IMStruct002 struct002) {

        }

        @Override
        public void updateProgress(IMStruct002 struct002, double percent) {
            if (percent == -1.0d) {
                JFMessageManager.getInstance().updateMessage(struct002);
            }
            notifyDataSetChanged();
        }

        @Override
        public void sendPreMessage(final IMStruct002 struct002) {
            if (struct002 != null) {
                messageManager = JFMessageManager.getInstance();
                messageManager.sendPreMessage(struct002);
            }
        }
    };
    ChatListView chatListView;


    public ChatAdapter(Context context, ChatListView chatListView,
                       List<IMStruct002> datas) {
        this.mContext = context;
        // initImageLoader();
        lxGlideImageLoader = new LXGlideImageLoader();
        if (datas == null) {
            datas = new ArrayList<IMStruct002>(0);
        }
        this.datas = datas;
        this.chatListView = chatListView;
        myhandler = new Myhandler();
        try {
            myUserId = Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        viewTypeDelegate = new ChatMessageViewTypeDelegate(myUserId);
        DownloadManager.getInstance().addDownloadListener(this);
    }

    /*
     * adpter 刷新方法
     */
    public void refresh(List<IMStruct002> datas) {
        if (datas == null) {
            datas = new ArrayList<IMStruct002>(0);
        }
        this.datas = datas;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    // 每个convert view都会调用此方法，获得当前所需要的view样式
    @Override
    public int getItemViewType(int position) {
        IMStruct002 iMStruct002 = (IMStruct002) getItem(position);
        return viewTypeDelegate.getItemViewType(iMStruct002);
    }

    @Override
    public int getViewTypeCount() {
        return viewTypeDelegate.getViewTypeCount();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final IMStruct002 iMStruct002 = (IMStruct002) datas.get(position);

        int type = getItemViewType(position);
        if (convertView == null) {
            switch (type) {
                case VIEW_TYPE_OUTGOING:// 发送container
                    convertView = new MessageOutgoingView(mContext);
                    break;
                case VIEW_TYPE_INCOMMING: // 接受container
                    convertView = new MessageIncomingView(mContext);
                    break;
                case VIEW_TYPE_OFFICIAL_ACCTOUNT:// 公众号container
                    convertView = new MessagePublicNumberView(mContext);
                    break;
                case VIEW_TYPE_TIPS://撤回消息container
                    convertView = new MessageRecallView(mContext);
                    break;
                case VIEW_TYPE_SYSTEM:
                    convertView = new MessageHideView(mContext);
                    break;
            }
        }

        final MessageBaseView messageBaseView = (MessageBaseView) convertView;

        IMessageItem imessageItem = null;
        final int messageChildType = iMStruct002.getMessageChildType();
        messageBaseView.setSupplementVisible(false);
        switch (messageChildType) {
            case MessageChildTypeConstant.subtype_text:
            case MessageChildTypeConstant.subtype_officalAccount:
            case MessageChildTypeConstant.subtype_callingCard:
            case MessageChildTypeConstant.subtype_payCard:
            case MessageChildTypeConstant.subtype_task:// 任务
                // messageBaseView.setSupplementVisible(true);
            case MessageChildTypeConstant.subtype_image:// 图片
            case MessageChildTypeConstant.subtype_smallVideo:// 视频
            case MessageChildTypeConstant.subtype_location://位置
            case MessageChildTypeConstant.subtype_feiyongbaoxiao://费用报销
            case MessageChildTypeConstant.subtype_oa://oa
            case MessageChildTypeConstant.subtype_recallMessage://撤回消息
            case MessageChildTypeConstant.subtype_mZoneNotification://空间通知
            case MessageChildTypeConstant.subtype_voice:// 语音
            case MessageChildTypeConstant.subtype_officalweb:// 网页
            case MessageChildTypeConstant.subtype_common:// 通用页面
            case MessageChildTypeConstant.subtype_file:// 文件
            case MessageChildTypeConstant.subtype_xj_item1://新疆item1
            case MessageChildTypeConstant.subtype_zy_task://中油铁工item
            case MessageChildTypeConstant.subtype_TangZuItem://糖足消息item
            case MessageChildTypeConstant.subtype_meeting://会议消息item
            case MessageChildTypeConstant.subtype_recognition://面部识别消息item
            case MessageChildTypeConstant.subtype_gxtask://共享任务消息item
            case MessageChildTypeConstant.subtype_form:
            case MessageChildTypeConstant.subtype_anim:// 动画
            case MessageChildTypeConstant.subtype_transfer://转账
            case MessageChildTypeConstant.subtype_secret_text://密信
            case MessageChildTypeConstant.subtype_secret_image://密图
            case MessageChildTypeConstant.subtype_secret_file://密件
                imessageItem = JFMessageItemManager.getMessageItem(mContext, iMStruct002);
                break;
            case MessageChildTypeConstant.subtype_bornText:
                DismissCallbacks mCallbacks = new DismissCallbacks() {
                    @Override
                    public void onDismiss(View view, Object token) {
                        datas.remove(position);
                        refresh(datas);
                    }

                    @Override
                    public boolean canDismiss(Object token) {
                        return true;
                    }
                };
                byte[] body1 = iMStruct002.getBody();
                Spannable text = SmileUtils.getSmiledText(mContext, new String(
                        body1));
                imessageItem = new TextMessageItemForDes(mContext, chatListView,
                        convertView, text, mCallbacks);
                break;
            default:
                // TODO: 17-8-13 其他的类型先显示字符串，防止程序崩溃
                imessageItem = JFMessageItemManager.getMessageItem(mContext, iMStruct002);
                break;
        }

        // TODO 设置iMStruct002
        if (!iMStruct002.isRecall()) {
            if (messageChildType == MessageChildTypeConstant.subtype_file) {
                //文件
                IMStruct002 imStruct002 = IMStruct002Util.getImStruct002(iMStruct002, position);
                imessageItem.setIMStruct002(imStruct002);
            } else if (messageChildType == MessageChildTypeConstant.subtype_image) {
                //图片
                ((ImageMessageItem) imessageItem).setMessageList(datas);
                imessageItem.setIMStruct002(iMStruct002);
            } else {
                imessageItem.setIMStruct002(iMStruct002);
            }
        } else {
            imessageItem.setIMStruct002(iMStruct002);
        }
        // TODO 设置MessageItem
        messageBaseView.setMessageItem(imessageItem);
        //TODO 设置文字消息双击事件
        if (messageChildType == MessageChildTypeConstant.subtype_text && !iMStruct002.isRecall()) {
            messageBaseView.getMessageItem().messageView().setOnClickListener(new View
                    .OnClickListener() {
                int count = 0;
                long firstClickTime = 0;
                long secondClickTime = 0;

                @Override
                public void onClick(View view) {
                    // 如果第二次点击 距离第一次点击时间过长 那么将第二次点击看为第一次点击
                    if (firstClickTime != 0 && System.currentTimeMillis() - firstClickTime >
                            500) {
                        count = 0;
                    }
                    count++;
                    if (count == 1) {
                        firstClickTime = System.currentTimeMillis();
                    } else if (count == 2) {
                        secondClickTime = System.currentTimeMillis();
                        // 两次点击小于500ms 也就是连续点击
                        if (secondClickTime - firstClickTime < 500) {
                            //ToastUtil.showToast(mContext, "双击");
                            ChatMessageMenuDialogUtil.showBigTextView(mContext, iMStruct002);
                            count = 0;
                            firstClickTime = 0;
                            secondClickTime = 0;
                        }
                    }
                }
            });
        }

        //TODO:消息长按事件
        messageBaseView.getMessageItem().messageView().setOnLongClickListener(new View
                .OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                ChatMessageMenuDialogUtil.showDialog(mContext, iMStruct002, ChatAdapter.this);
                return false;
            }
        });

        // 文件item点击 记录当前正在下载的条目position
        if (messageChildType == MessageChildTypeConstant.subtype_file && !iMStruct002.isRecall()) {
            messageBaseView.getMessageItem().messageView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    FileMessageItem item = (FileMessageItem) messageBaseView.getMessageItem().messageView();
                    item.clickItem();
                }
            });
        }

        //  TODO topView 设置时间
        if (position == 0) {
            messageBaseView.getTopTextView().setText(ChatDateUtils.getTimestampString(
                    new Date(iMStruct002.getTime())));
            messageBaseView.getTopTextView().setVisibility(View.VISIBLE);
        } else {
            // 两条消息时间离得如果稍长，显示时间
            if (position - 1 >= 0) {
                if (ChatDateUtils.isCloseEnough(iMStruct002.getTime(), datas
                        .get(position - 1).getTime())) {
                    messageBaseView.getTopTextView().setVisibility(View.GONE);
                } else {
                    messageBaseView.getTopTextView().setText(ChatDateUtils.getTimestampString(
                            new Date(iMStruct002.getTime())));
                    messageBaseView.getTopTextView().setVisibility(View.VISIBLE);
                }
            } else {
                messageBaseView.getTopTextView().setVisibility(View.GONE);
            }
        }

        // TODO 设置用户名是否显示（群组显示用户名）
        if (iMStruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP
                && Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)) != iMStruct002
                .getFromUserId()) {
            messageBaseView.getUserNameTextView().setVisibility(View.VISIBLE);
            String name = "";
            User user = GroupNameUtil.getGroupUser(iMStruct002.getToUserId(),
                    iMStruct002.getFromUserId());
            name = GroupNameUtil.getGroupUserName(user);
            messageBaseView.getUserNameTextView().setText(name);
        } else {
            messageBaseView.getUserNameTextView().setVisibility(View.INVISIBLE);
        }

        // TODO 设置用户头像
        final User user = WeChatDBManager.getInstance().getOneUserById(iMStruct002.getFromUserId());
        String avatarString = user.getAvatar();
        lxGlideImageLoader.showUserAvatar(mContext, messageBaseView.getAvatarImageView(), avatarString);

        // TODO 用户头像点击事件
        messageBaseView.getAvatarImageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = null;
                if (iMStruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {
                    intent = new Intent();
                    intent.putExtra("id", user.getId());
                    intent.putExtra("groupId", iMStruct002.getToUserId());
                    //mContext.startActivity(intent);
                    ChatActivitySkipUtil.startUserInfoActivity(mContext, intent);
                } else {
                    intent = new Intent();
                    intent.putExtra("id", user.getId());
                    ChatActivitySkipUtil.startUserInfoActivity(mContext, intent);
                }

            }
        });

        //TODO 设置消息发送状态
        if (convertView instanceof MessageOutgoingView) {
            int state = iMStruct002.getState();
            switch (state) {
                case IMStruct002.MESSAGE_STATE_SENDING:
                    ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.VISIBLE);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).setSupplementVisible(true);
                    ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_sending);
                    break;
                case IMStruct002.MESSAGE_STATE_WAITSEND:
                    ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.VISIBLE);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).setSupplementVisible(true);
                    ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_pending);
                    break;
                case IMStruct002.MESSAGE_STATE_PRESEND:
                    //预发送,进度为0，待发送
                    //进度为其他不为-1数值，正在发送
                    Long startUpLoadTime = (Long) iMStruct002.getExtra("startUploadTime");
                    if (startUpLoadTime == null) {
                        startUpLoadTime = System.currentTimeMillis();
                    }
                    //一分钟发送出不出去就是超时了
                    boolean isTimeOut = System.currentTimeMillis() - startUpLoadTime > 1000 * 60;
                    if (isTimeOut && iMStruct002.getExtra("progress") != null && (int) iMStruct002.getExtra("progress") != -1) {
                        iMStruct002.putExtra("progress", -1);
                        JFMessageManager.getInstance().updateMessage(iMStruct002);
                        notifyDataSetChanged();
                    }
                    if (iMStruct002.getExtra("progress") != null && (int) iMStruct002.getExtra("progress") != -1) {
                        ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.VISIBLE);
                        ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                        ((MessageBaseView) convertView).setSupplementVisible(true);
                        ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_pending);
                    } else {
                        //进度为空，但是停留在预发送状态，发送失败，重新发送（以前的版本）
                        //发送失败，进度为-1，重新发送
                        ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.GONE);
                        ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View
                                .VISIBLE);
                        ((MessageBaseView) convertView).setSupplementVisible(false);
                        ((MessageBaseView) convertView).getLoadingErrorImage().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                                builder.setItems(R.array.chat_message,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog,
                                                                int which) {
                                                if (which == 0) {
                                                    String msgPath;
                                                    if (messageChildType == MessageChildTypeConstant.subtype_file
                                                            || messageChildType == MessageChildTypeConstant.subtype_secret_file) {
                                                        msgPath = JSONUtil.parseJson(iMStruct002.getMessage()).get("FileLocalPath").getAsString();
                                                    } else if (messageChildType == MessageChildTypeConstant.subtype_location) {
                                                        msgPath = JSONUtil.parseJson(iMStruct002.getMessage()).get("localPath").getAsString();
                                                    } else {
                                                        msgPath = JSONUtil.parseJson(iMStruct002.getMessage()).get("path").getAsString();
                                                    }
                                                    //重新发送进度设为0 刷新界面
                                                    iMStruct002.putExtra("progress", 0);
                                                    iMStruct002.putExtra("startUploadTime", System.currentTimeMillis());
                                                    notifyDataSetChanged();
                                                    MessagePanSoftUtils.upload(msgPath, iMStruct002, preSendMessageCallback, messageChildType);
                                                } else if (which == 1) {
                                                    dialog.dismiss();
                                                }
                                            }
                                        });
                                builder.show();
                            }
                        });
                    }
                    break;
                case IMStruct002.MESSAGE_STATE_SEND:
                    ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).setSupplementVisible(true);
                    ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_sended);
                    break;
                case MESSAGE_STATE_DELIVER:
                    ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).setSupplementVisible(true);
                    ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_delivered);
                    break;
                case IMStruct002.MESSAGE_STATE_RECEIVE:
                    ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).setSupplementVisible(true);
                    ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_received);
                    break;
                case IMStruct002.MESSAGE_STATE_READ:
                    ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).setSupplementVisible(true);
                    ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_read);
                    break;
                case IMStruct002.MESSAGE_STATE_FAILURE:
                    ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.GONE);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View
                            .VISIBLE);
                    ((MessageBaseView) convertView).setSupplementVisible(false);
                    ((MessageBaseView) convertView).getLoadingErrorImage().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                            builder.setItems(R.array.chat_message,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            if (which == 0) {
                                                datas.remove(iMStruct002);
                                                //重发消息b
                                                iMStruct002.setState(-1);
                                                JFMessageManager.getInstance().reSendMessage
                                                        (iMStruct002);
                                                notifyDataSetChanged();
                                            } else if (which == 1) {
                                                dialog.dismiss();
                                            }
                                        }
                                    });
                            builder.show();
                        }
                    });

                    break;
                default:
                    break;
            }
            //群组消息没有已送达
            if (iMStruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP
                    && state == IMStruct002.MESSAGE_STATE_READ) {
                ((MessageBaseView) convertView).getMprogressbar().setVisibility(View.GONE);
                ((MessageBaseView) convertView).getLoadingErrorImage().setVisibility(View.GONE);
                ((MessageBaseView) convertView).setSupplementVisible(true);
                ((MessageBaseView) convertView).getChatStateView().setText(R.string.wechat_chat_state_sended);
            }
        }
        return convertView;
    }


    @Override
    public void downLoadCallBack(String result) {
        myhandler.sendEmptyMessage(1);

    }


    public class Myhandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                notifyDataSetChanged();
            }
        }
    }

    public void removeDownLoadListener() {
        DownloadManager.getInstance().removeDownLoadListener();
    }
}